// pages/chat/chat.js
var request_url = "http://hisi.kder.top/";
var websocket_url = "wss://ik.kder.top:9501";

// lmhilpxuaJhgmm+V => 1
// l2hilpxvYptlmGqV  => 2
Page({
  data: {
    allContentList: [],
    inputValue: '',
  },

  onLoad: function () {
    this.getChatLists();

    this.socketInit();
  },

  getChatLists: function () {
    var that = this;
    wx.request({
      url: request_url + '/im/chat/history',
      data: {
        token: "lmhilpxuaJhgmm+V",
        obj_uid: 2
      },
      method: "POST",
      success: function (res) {
        console.log("history", res.data.history);
        that.setData({
          allContentList: res.data.history
        });
      }
    })
  },

  socketInit: function () {
    var that = this;
    // 建立连接
    wx.connectSocket({
      url: websocket_url,
      success: res => {
        console.log("connectSocket success\n", res);
      },
    });

    // 监听新消息进入
    wx.onSocketMessage(function (res) {
      
      var data = JSON.parse(res.data)
      console.log("onSocketMessage success\n", data);

      switch (data.type){
        case "init":
          wx.sendSocketMessage({
            data: JSON.stringify({
              type: "init",
              token: "lmhilpxuaJhgmm+V",
            }),
          })
          break;
        case "newMess":
          that.data.allContentList.push({
            content: data.content,
            is_mine: 0,
          });
          that.setData({
            allContentList: that.data.allContentList,
            inputValue: '',
          });
          break;
        default:

          break;
      }
    })
  },

  send: function (e) {
    var that = this;
    var content = that.data.inputValue;

    wx.request({
      url: request_url + '/im/chat/save',
      data: {
        token: "lmhilpxuaJhgmm+V",
        obj_uid: 2,
        root_id: 0,
        content: content
      },
      header: {
        'Content-Type': 'application/json'
      },
      method: "POST",
      success: function (res) {
        that.data.allContentList.push({
          content: content,
          is_mine: 1,
        });
        that.setData({
          allContentList: that.data.allContentList,
          inputValue: '',
        });

        // 通知对方
        wx.sendSocketMessage({
          data: JSON.stringify({
            type: "newMess",
            obj_token: "l2hilpxvYptlmGqV",
            content:content
          }),
        });
      }
    })

  },

  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  }
})